package cn.gson.boot.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.gson.boot.model.pojos.User;
import cn.gson.boot.model.service.EmpService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadTouXiangController {
    String uri = "E:/upload";

    @Autowired
    EmpService empService;

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file")
                                 MultipartFile file, HttpSession session) {
        String fileName = file.getOriginalFilename();
        System.err.println("fileName:"+fileName);
        String ext = FilenameUtils.getExtension(fileName);
        //生成一个新的名字
        String newName = UUID.randomUUID().toString();
        String filePath = newName + ".jpg" + ext;
        try {
            File f = new File(uri,filePath);
            if(!f.exists()) {
                f.mkdirs();//如果目录不存在，创建
            }
            //文件转移
            file.transferTo(f);
            //将路径存进数据库
            User user = (User)session.getAttribute("user");
            System.out.println("头像上传："+user);
            empService.updteEmpImgByEmpId("upload/" + filePath,user.getEmpId());
            //回显路径
            return  "upload/" + filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("upload/**")
    @ResponseBody
    public void upload(HttpServletRequest request,
                       HttpServletResponse response) {
        //System.err.println("进来了吗我：杀杀杀杀杀杀杀杀杀");
        String servletPath = request.getServletPath();
        String path = uri + "/" + servletPath.replaceFirst("/upload/","");
        //System.out.println("path:"+path);
        //判断
        File file = new File(path);
        if(!file.exists()) {
            //抛出异常
            try {
                response.sendError(404, "文件路径不存在");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            //使用字节流把图片从本地盘中读取到内存
            InputStream is = new FileInputStream(file);
            //servlet中的流将图片传回客户端显示
            ServletOutputStream s = response.getOutputStream();
            //System.out.println("sss:");
            byte[] b = new byte[1024];
            int len = 0;
            //循环读取
            while((len = is.read(b))!= -1) {
                s.write(b, 0, len);
            }
            s.close();
            is.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
